﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Reflection;

namespace BlogHunter
{
    class BlogFactory
    {
        private static readonly string AssemblyName = "BlogHunter";
        private static readonly string blogDomainList = ConfigurationSettings.AppSettings["BlogDomainList"];
        private static readonly string[] blogDomainArray = ConfigurationSettings.AppSettings["BlogDomainList"].Split('|');

        /// <summary>
        /// Get Blog By blogDomain
        /// </summary>
        /// <param name="blogDomain"></param>
        /// <returns></returns>
        private static Blog GetBlog(String blogDomain)
        {
            if (!String.IsNullOrEmpty(blogDomain) && blogDomainList.Contains(blogDomain))
            {
                String blogClassName = ConfigurationSettings.AppSettings[blogDomain];
                String className = AssemblyName + "." + blogClassName;

                return (Blog)Assembly.Load(AssemblyName).CreateInstance(className);
            }
            else
            {
                return null;
            }
        }

        public static Blog GetBlog(string inputBlogName, Uri uri)
        {
            for (int i = 0; i < blogDomainArray.Length; i++)
            {
                String tempBlogDomain = blogDomainArray[i];
                if (!String.IsNullOrEmpty(tempBlogDomain))
                {
                    if (uri.AbsoluteUri.Contains(tempBlogDomain))
                    {
                        Blog blog = GetBlog(tempBlogDomain);
                        if (blog != null)
                        {
                            //Generate Blog Home Page Uri
                            blog.InputBlogName = inputBlogName;
                            blog.InputBlogHomePage = uri;
                            blog.GenerateBlogHomePage();

                            //Generate XML File Path
                            blog.GenerateXMLFilePath();
                        }
                        return blog;
                    }
                }
            }
            return null;
        }
    }
}
